<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>舞蹈姿态分析器</title>
    <script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils@0.6.1675466023/control_utils.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils@0.3.1675466124/drawing_utils.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@mediapipe/pose@0.5.1675469404/pose.min.js "></script>
    <link href="
https://cdn.jsdelivr.net/npm/@mediapipe/control_utils@0.6.1675466023/control_utils.min.css
" rel="stylesheet">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #333;
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            color: #666;
            font-size: 1.2em;
            margin-bottom: 10px;
        }
        
        .video-container {
            position: relative;
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        
        #input_video {
            display: none;
        }
        
        #output_canvas {
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            max-width: 100%;
            height: auto;
        }
        
        .score-panel {
            background: linear-gradient(135deg, #ff6b9d, #ff8a9b);
            border-radius: 20px;
            padding: 30px;
            text-align: center;
            color: white;
            margin-top: 20px;
            position: relative;
            overflow: hidden;
        }
        
        .score-panel::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: shimmer 3s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .score-title {
            font-size: 1.2em;
            margin-bottom: 15px;
            opacity: 0.9;
        }
        
        .score-value {
            font-size: 4em;
            font-weight: bold;
            margin: 10px 0;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .stars {
            font-size: 2em;
            margin: 15px 0;
        }
        
        .feedback {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            font-size: 1.1em;
            line-height: 1.5;
            text-align: left;
            max-height: 120px;
            overflow-y: auto;
        }
        
        .controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 20px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: bold;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .btn-primary:disabled:hover {
            transform: none;
            box-shadow: none;
        }
        
        .btn-secondary {
            background: #f8f9fa;
            color: #333;
            border: 2px solid #dee2e6;
        }
        
        .btn-secondary:hover {
            background: #e9ecef;
            transform: translateY(-2px);
        }
        
        .pose-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        
        .pose-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            border-left: 4px solid #667eea;
        }
        
        .pose-card h3 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .pose-card p {
            color: #666;
            font-size: 1.1em;
            font-weight: bold;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .camera-status {
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 1em;
            font-weight: bold;
            margin: 15px auto;
            display: inline-block;
            min-width: 200px;
            text-align: center;
        }
        
        .camera-status.loading {
            background: linear-gradient(135deg, #ffeaa7, #fdcb6e);
            color: #2d3436;
        }
        
        .camera-status.success {
            background: linear-gradient(135deg, #55efc4, #00b894);
            color: white;
        }
        
        .camera-status.error {
            background: linear-gradient(135deg, #fd79a8, #e84393);
            color: white;
        }
        
        .camera-status.info {
            background: linear-gradient(135deg, #74b9ff, #0984e3);
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🩰 舞蹈姿态分析器</h1>
            <p>基于 MediaPipe 的实时舞蹈动作评分系统</p>
            <div id="cameraStatus" class="camera-status loading">正在检查摄像头...</div>
        </div>
        
        <div class="loading" id="loading" style="display: none;">
            <div class="spinner"></div>
            <p>正在初始化摄像头和AI模型...</p>
        </div>
        
        <div class="video-container" style="display: none;">
            <video id="input_video" autoplay muted playsinline></video>
            <canvas id="output_canvas"></canvas>
        </div>
        
        <div class="score-panel" id="scorePanel">
            <div class="score-title">动作评分</div>
            <div class="score-value" id="scoreValue">0</div>
            <div class="stars" id="stars">☆☆☆☆☆</div>
            <div class="feedback" id="feedback">等待开始分析...</div>
            <button class="btn btn-secondary" onclick="shareScore()">
                📤 分享成绩
            </button>
        </div>
        
        <div class="controls">
            <button class="btn btn-primary" onclick="startAnalysis()" id="startBtn">
                🎯 开始分析
            </button>
            <button class="btn btn-secondary" onclick="stopAnalysis()" id="stopBtn" disabled>
                ⏹️ 停止分析
            </button>
            <button class="btn btn-secondary" onclick="resetAnalysis()" id="resetBtn" disabled>
                🔄 重新开始
            </button>
        </div>
        
        <div class="pose-info" id="poseInfo" style="display: none;">
            <div class="pose-card">
                <h3>姿态稳定性</h3>
                <p id="stability">0%</p>
            </div>
            <div class="pose-card">
                <h3>关节角度</h3>
                <p id="angles">完美</p>
            </div>
            <div class="pose-card">
                <h3>平衡度</h3>
                <p id="balance">优秀</p>
            </div>
            <div class="pose-card">
                <h3>流畅度</h3>
                <p id="fluidity">85%</p>
            </div>
        </div>
    </div>

    <script>
        let pose;
        let isAnalyzing = false;
        let frameCount = 0;
        let poseHistory = [];
        let currentScore = 0;
        let cameraStream = null; // 存储摄像头流
        let cameraReady = false; // 摄像头是否准备就绪
        
        // 检查浏览器兼容性
        function checkBrowserCompatibility() {
            const issues = [];
            
            // 检查基本API支持
            if (!navigator.mediaDevices) {
                issues.push('不支持媒体设备API');
            }
            
            if (!navigator.mediaDevices.getUserMedia) {
                issues.push('不支持摄像头访问');
            }
            
            if (!window.requestAnimationFrame) {
                issues.push('不支持动画帧API');
            }
            
            if (!document.createElement('canvas').getContext) {
                issues.push('不支持Canvas');
            }
            
            // 检查是否为HTTPS环境（本地localhost除外）
            if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                issues.push('需要HTTPS环境才能访问摄像头');
            }
            
            // 检查Chrome版本（如果是Chrome）
            const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
            if (isChrome) {
                const chromeVersion = navigator.userAgent.match(/Chrome\/(\d+)/);
                if (chromeVersion && parseInt(chromeVersion[1]) < 60) {
                    issues.push('Chrome版本过低，建议升级到60+');
                }
            }
            
            return issues;
        }
        
        // 显示兼容性警告
        function showCompatibilityWarning(issues) {
            if (issues.length === 0) return;
            
            const warningDiv = document.createElement('div');
            warningDiv.style.cssText = `
                background: linear-gradient(135deg, #fd79a8, #e84393);
                color: white;
                padding: 15px;
                border-radius: 10px;
                margin: 15px 0;
                font-weight: bold;
            `;
            
            warningDiv.innerHTML = `
                <div style="margin-bottom: 10px;">⚠️ 浏览器兼容性问题：</div>
                <ul style="margin: 0; padding-left: 20px;">
                    ${issues.map(issue => `<li>${issue}</li>`).join('')}
                </ul>
                <div style="margin-top: 10px; font-size: 0.9em; opacity: 0.9;">
                    建议使用最新版本的Chrome、Firefox或Edge浏览器
                </div>
            `;
            
            const header = document.querySelector('.header');
            header.appendChild(warningDiv);
        }
        
        // 检查摄像头权限和设备
        async function checkCameraPermission() {
            try {
                // 检查是否支持 getUserMedia
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('此浏览器不支持摄像头访问');
                }
                
                // Chrome 中直接尝试枚举设备（不检查权限API，因为可能不支持）
                try {
                    const devices = await navigator.mediaDevices.enumerateDevices();
                    const videoDevices = devices.filter(device => device.kind === 'videoinput');
                    
                    if (videoDevices.length === 0) {
                        showCameraStatus('未检测到摄像头设备', 'error');
                        return false;
                    }
                    
                    console.log('检测到摄像头设备:', videoDevices.length);
                    return true;
                } catch (enumError) {
                    console.log('设备枚举失败，但继续尝试获取摄像头');
                    return true; // 即使枚举失败，也尝试获取摄像头
                }
                
            } catch (error) {
                console.error('摄像头检查失败:', error);
                showCameraStatus('摄像头检查失败: ' + error.message, 'error');
                return false;
            }
        }
        
        // 预先获取摄像头权限
        async function requestCameraAccess() {
            try {
                showCameraStatus('正在请求摄像头权限...', 'loading');
                
                // 使用Chrome兼容的getUserMedia配置
                const constraints = {
                    video: {
                        width: { ideal: 640, max: 1280 },
                        height: { ideal: 480, max: 720 },
                        frameRate: { ideal: 30, max: 60 }
                    },
                    audio: false
                };
                
                // 尝试获取前置摄像头
                try {
                    constraints.video.facingMode = 'user';
                    cameraStream = await navigator.mediaDevices.getUserMedia(constraints);
                } catch (facingError) {
                    // 如果前置摄像头失败，尝试任意摄像头
                    console.log('前置摄像头不可用，尝试任意摄像头');
                    delete constraints.video.facingMode;
                    cameraStream = await navigator.mediaDevices.getUserMedia(constraints);
                }
                
                cameraReady = true;
                showCameraStatus('摄像头已准备就绪 ✅', 'success');
                
                // 更新开始按钮状态
                const startBtn = document.getElementById('startBtn');
                startBtn.disabled = false;
                startBtn.textContent = '🎯 开始分析';
                
                return true;
                
            } catch (error) {
                console.error('摄像头权限获取失败:', error);
                cameraReady = false;
                
                let errorMessage = '摄像头权限获取失败';
                if (error.name === 'NotAllowedError') {
                    errorMessage = '摄像头权限被拒绝，请点击地址栏左侧的摄像头图标允许访问';
                } else if (error.name === 'NotFoundError') {
                    errorMessage = '未找到摄像头设备';
                } else if (error.name === 'NotReadableError') {
                    errorMessage = '摄像头正在被其他应用使用，请关闭其他应用后刷新页面';
                } else if (error.name === 'OverconstrainedError') {
                    errorMessage = '摄像头不支持所需配置，请尝试其他摄像头';
                } else if (error.name === 'SecurityError') {
                    errorMessage = '需要HTTPS环境才能访问摄像头';
                }
                
                showCameraStatus(errorMessage, 'error');
                
                // 更新开始按钮状态
                const startBtn = document.getElementById('startBtn');
                startBtn.disabled = true;
                startBtn.textContent = '❌ 摄像头不可用';
                
                return false;
            }
        }
        
        // 显示摄像头状态
        function showCameraStatus(message, type = 'info') {
            const statusElement = document.getElementById('cameraStatus');
            if (statusElement) {
                statusElement.textContent = message;
                statusElement.className = `camera-status ${type}`;
            }
        }
        
        // 初始化MediaPipe姿态检测
        async function initializePoseDetection() {
            try {
                showCameraStatus('正在加载AI模型...', 'loading');
                
                // 检查MediaPipe支持
                if (typeof window.Pose === 'undefined') {
                    throw new Error('MediaPipe未正确加载');
                }
                
                // 创建姿态检测器
                pose = new Pose({
                    locateFile: (file) => {
                        // 使用CDN加载MediaPipe文件
                        return `https://cdn.jsdelivr.net/npm/@mediapipe/pose/${file}`;
                    }
                });
                
                // 配置姿态检测选项
                await pose.setOptions({
                    modelComplexity: 1,
                    smoothLandmarks: true,
                    enableSegmentation: false,
                    smoothSegmentation: false,
                    minDetectionConfidence: 0.5,
                    minTrackingConfidence: 0.5
                });
                
                // 设置结果回调
                pose.onResults(onPoseResults);
                
                showCameraStatus('AI模型加载完成', 'success');
                return true;
                
            } catch (error) {
                console.error('MediaPipe初始化失败:', error);
                showCameraStatus('AI模型加载失败: ' + error.message, 'error');
                
                // 提供降级方案提示
                const warningDiv = document.createElement('div');
                warningDiv.style.cssText = `
                    background: linear-gradient(135deg, #ffeaa7, #fdcb6e);
                    color: #2d3436;
                    padding: 15px;
                    border-radius: 10px;
                    margin: 15px 0;
                    font-weight: bold;
                `;
                
                warningDiv.innerHTML = `
                    <div style="margin-bottom: 10px;">💡 建议解决方案：</div>
                    <ul style="margin: 0; padding-left: 20px;">
                        <li>刷新页面重新加载AI模型</li>
                        <li>检查网络连接是否正常</li>
                        <li>尝试使用无痕浏览模式</li>
                        <li>清除浏览器缓存后重试</li>
                    </ul>
                `;
                
                const header = document.querySelector('.header');
                header.appendChild(warningDiv);
                
                return false;
            }
        }
        
        // 处理姿态检测结果
        function onPoseResults(results) {
            if (!results.poseLandmarks) return;
            
            const canvas = document.getElementById('output_canvas');
            const ctx = canvas.getContext('2d');
            const video = document.getElementById('input_video');
            
            // 设置画布尺寸
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制姿态关键点
            drawPose(ctx, results.poseLandmarks, canvas.width, canvas.height);
            
            // 分析舞蹈姿态
            analyzeDancePose(results.poseLandmarks);
        }
        
        // 绘制姿态关键点
        function drawPose(ctx, landmarks, width, height) {
            // 姿态连接线定义
            const connections = [
                [11, 12], [11, 13], [13, 15], [12, 14], [14, 16], // 肩膀和手臂
                [11, 23], [12, 24], [23, 24], // 躯干
                [23, 25], [25, 27], [24, 26], [26, 28], // 腿部
                [27, 29], [29, 31], [28, 30], [30, 32], // 脚部
                [15, 17], [15, 19], [15, 21], [16, 18], [16, 20], [16, 22], // 手部
                [17, 19], [18, 20], [27, 31], [28, 32] // 手指和脚趾
            ];
            
            // 绘制连接线
            ctx.strokeStyle = '#FFD700';
            ctx.lineWidth = 3;
            connections.forEach(([start, end]) => {
                const startPoint = landmarks[start];
                const endPoint = landmarks[end];
                if (startPoint && endPoint && startPoint.visibility > 0.5 && endPoint.visibility > 0.5) {
                    ctx.beginPath();
                    ctx.moveTo(startPoint.x * width, startPoint.y * height);
                    ctx.lineTo(endPoint.x * width, endPoint.y * height);
                    ctx.stroke();
                }
            });
            
            // 绘制关键点
            ctx.fillStyle = '#FF69B4';
            landmarks.forEach((landmark, index) => {
                if (landmark.visibility > 0.5) {
                    ctx.beginPath();
                    ctx.arc(landmark.x * width, landmark.y * height, 5, 0, 2 * Math.PI);
                    ctx.fill();
                }
            });
        }
        
        // 分析舞蹈姿态
        function analyzeDancePose(landmarks) {
            if (!isAnalyzing) return;
            
            let score = 0;
            let feedback = [];
            
            // 检查姿态稳定性
            const leftShoulder = landmarks[11];
            const rightShoulder = landmarks[12];
            const leftHip = landmarks[23];
            const rightHip = landmarks[24];
            
            if (leftShoulder && rightShoulder && leftHip && rightHip) {
                // 计算身体平衡度
                const shoulderBalance = Math.abs(leftShoulder.y - rightShoulder.y);
                const hipBalance = Math.abs(leftHip.y - rightHip.y);
                
                if (shoulderBalance < 0.05 && hipBalance < 0.05) {
                    score += 20;
                    feedback.push('✅ 身体平衡良好');
                } else {
                    feedback.push('⚠️ 注意身体平衡');
                }
                
                // 检查姿态挺拔度
                const shoulderMidpoint = (leftShoulder.y + rightShoulder.y) / 2;
                const hipMidpoint = (leftHip.y + rightHip.y) / 2;
                const posture = hipMidpoint - shoulderMidpoint;
                
                if (posture > 0.15) {
                    score += 15;
                    feedback.push('✅ 姿态挺拔');
                } else {
                    feedback.push('⚠️ 保持挺胸收腹');
                }
            }
            
            // 检查手臂动作
            const leftWrist = landmarks[15];
            const rightWrist = landmarks[16];
            const leftElbow = landmarks[13];
            const rightElbow = landmarks[14];
            
            if (leftWrist && rightWrist && leftElbow && rightElbow) {
                // 检查手臂对称性
                const leftArmHeight = Math.abs(leftWrist.y - leftElbow.y);
                const rightArmHeight = Math.abs(rightWrist.y - rightElbow.y);
                const armSymmetry = Math.abs(leftArmHeight - rightArmHeight);
                
                if (armSymmetry < 0.1) {
                    score += 15;
                    feedback.push('✅ 手臂动作协调');
                } else {
                    feedback.push('⚠️ 注意手臂对称性');
                }
            }
            
            // 检查腿部动作
            const leftKnee = landmarks[25];
            const rightKnee = landmarks[26];
            const leftAnkle = landmarks[27];
            const rightAnkle = landmarks[28];
            
            if (leftKnee && rightKnee && leftAnkle && rightAnkle) {
                // 检查腿部稳定性
                const legStability = Math.abs(leftKnee.x - rightKnee.x);
                
                if (legStability > 0.1) {
                    score += 10;
                    feedback.push('✅ 腿部动作有力');
                } else {
                    feedback.push('⚠️ 加强腿部动作');
                }
            }
            
            // 更新分数显示
            currentScore = Math.min(score, 100);
            document.getElementById('scoreValue').textContent = currentScore;
            
            // 更新反馈
            const feedbackElement = document.getElementById('feedback');
            feedbackElement.innerHTML = feedback.join('<br>');
            
            frameCount++;
        }
        
        // 开始分析
        async function startAnalysis() {
            if (!cameraReady || !cameraStream) {
                alert('摄像头未准备就绪，请检查摄像头权限');
                return;
            }
            
            try {
                showCameraStatus('正在启动分析...', 'loading');
                
                // 初始化MediaPipe
                const poseInitialized = await initializePoseDetection();
                if (!poseInitialized) {
                    return;
                }
                
                // 获取视频元素
                const video = document.getElementById('input_video');
                
                // 使用预先获取的摄像头流
                video.srcObject = cameraStream;
                
                // 等待视频开始播放
                await new Promise((resolve) => {
                    video.onloadedmetadata = () => {
                        video.play();
                        resolve();
                    };
                });
                
                // 显示视频容器
                const videoContainer = document.querySelector('.video-container');
                videoContainer.style.display = 'block';
                
                // 开始分析
                isAnalyzing = true;
                frameCount = 0;
                currentScore = 0;
                
                // 更新按钮状态
                const startBtn = document.getElementById('startBtn');
                const stopBtn = document.getElementById('stopBtn');
                const resetBtn = document.getElementById('resetBtn');
                
                startBtn.disabled = true;
                stopBtn.disabled = false;
                resetBtn.disabled = false;
                
                showCameraStatus('分析进行中...', 'success');
                
                // 开始视频处理循环
                processVideoFrame();
                
            } catch (error) {
                console.error('启动分析失败:', error);
                showCameraStatus('启动分析失败: ' + error.message, 'error');
            }
        }
        
        // 视频帧处理循环
        async function processVideoFrame() {
            if (!isAnalyzing) return;
            
            const video = document.getElementById('input_video');
            
            if (video.readyState >= 2) { // 视频已准备好
                try {
                    await pose.send({ image: video });
                } catch (error) {
                    console.error('姿态检测错误:', error);
                }
            }
            
            // 继续下一帧
            if (isAnalyzing) {
                requestAnimationFrame(processVideoFrame);
            }
        }
        
        // 停止分析
        function stopAnalysis() {
            isAnalyzing = false;
            
            // 更新按钮状态
            const startBtn = document.getElementById('startBtn');
            const stopBtn = document.getElementById('stopBtn');
            
            startBtn.disabled = false;
            stopBtn.disabled = true;
            
            showCameraStatus('分析已停止', 'info');
        }
        
        // 重置分析
        function resetAnalysis() {
            isAnalyzing = false;
            
            // 暂停视频但保持摄像头流活跃以保持权限
            const video = document.getElementById('input_video');
            video.pause();
            video.srcObject = null;
            
            // 清除画布
            const canvas = document.getElementById('output_canvas');
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 隐藏视频容器
            const videoContainer = document.querySelector('.video-container');
            videoContainer.style.display = 'none';
            
            // 重置数据
            frameCount = 0;
            currentScore = 0;
            
            // 重置显示
            document.getElementById('scoreValue').textContent = '0';
            document.getElementById('feedback').innerHTML = '等待开始分析...';
            
            // 更新按钮状态
            const startBtn = document.getElementById('startBtn');
            const stopBtn = document.getElementById('stopBtn');
            const resetBtn = document.getElementById('resetBtn');
            
            startBtn.disabled = false;
            stopBtn.disabled = true;
            resetBtn.disabled = true;
            
            showCameraStatus('已重置，准备开始新的分析', 'info');
        }
        
        // 分享分数
        function shareScore() {
            const score = document.getElementById('scoreValue').textContent;
            const text = `我在舞蹈姿态分析器中获得了 ${score} 分！🩰✨`;
            
            // 检查是否支持原生分享API
            if (navigator.share && navigator.canShare && navigator.canShare({ text: text })) {
                navigator.share({
                    title: '舞蹈姿态分析结果',
                    text: text,
                    url: window.location.href
                }).catch(err => {
                    console.log('分享取消或失败:', err);
                    fallbackShare(text);
                });
            } else {
                // 使用备用分享方法
                fallbackShare(text);
            }
        }
        
        // 备用分享方法
        function fallbackShare(text) {
            // 尝试使用剪贴板API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(() => {
                    showShareSuccess('分数已复制到剪贴板！可以粘贴到微信、QQ等应用分享');
                }).catch(err => {
                    console.error('复制失败:', err);
                    // 最后的备用方案
                    legacyShare(text);
                });
            } else {
                // 使用传统方法
                legacyShare(text);
            }
        }
        
        // 传统分享方法（兼容旧版浏览器）
        function legacyShare(text) {
            // 创建临时文本区域
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showShareSuccess('分数已复制到剪贴板！');
                } else {
                    showShareFallback(text);
                }
            } catch (err) {
                console.error('复制命令失败:', err);
                showShareFallback(text);
            }
            
            document.body.removeChild(textArea);
        }
        
        // 显示分享成功消息
        function showShareSuccess(message) {
            // 创建临时提示
            const toast = document.createElement('div');
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: linear-gradient(135deg, #55efc4, #00b894);
                color: white;
                padding: 15px 25px;
                border-radius: 10px;
                font-weight: bold;
                z-index: 10000;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 3000);
        }
        
        // 显示手动分享选项
        function showShareFallback(text) {
            const message = `请手动复制以下内容分享：\n\n${text}`;
            
            // 使用prompt作为最后的备用方案
            if (window.prompt) {
                window.prompt('请复制以下文本进行分享：', text);
            } else {
                alert(message);
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function() {
            console.log('舞蹈姿态分析器已准备就绪');
            
            // 检查浏览器兼容性
            const compatibilityIssues = checkBrowserCompatibility();
            if (compatibilityIssues.length > 0) {
                showCompatibilityWarning(compatibilityIssues);
                
                // 如果有严重兼容性问题，禁用功能
                if (compatibilityIssues.some(issue => 
                    issue.includes('不支持摄像头') || 
                    issue.includes('不支持媒体设备') ||
                    issue.includes('HTTPS环境')
                )) {
                    const startBtn = document.getElementById('startBtn');
                    startBtn.disabled = true;
                    startBtn.textContent = '❌ 浏览器不兼容';
                    showCameraStatus('浏览器不兼容，无法使用摄像头功能', 'error');
                    return;
                }
            }
            
            // 初始化时禁用开始按钮
            const startBtn = document.getElementById('startBtn');
            startBtn.disabled = true;
            startBtn.textContent = '🔄 检查摄像头...';
            
            // 检查摄像头权限和设备
            const hasCamera = await checkCameraPermission();
            
            if (hasCamera) {
                // 请求摄像头权限
                await requestCameraAccess();
            } else {
                startBtn.disabled = true;
                startBtn.textContent = '❌ 摄像头不可用';
            }
        });
    </script>
</body>
</html> 